//
//  TF_BackChatController.swift
//  TalkfunSDKDemo
//
//  Created by 邓盛明 on 2021/12/29.
//  Copyright © 2021 Talkfun. All rights reserved.
//

import UIKit

protocol TF_BackChatTableDelegate:class {
    func Backchat_clickToUrl(url:String)  
}
class TF_BackChatController: UIViewController,UITableViewDelegate,UITableViewDataSource, TF_BackChatUrlDelegate{
    
    var datasource:[TF_BackChatLiveData] = []
    var nodataView:UIView!
    var tableview:UITableView!
    var url:String!   
    var urlArr:[Any] = []
    weak var delegate: TF_BackChatTableDelegate?
    override func viewDidLoad() {
        super.viewDidLoad()

       
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.datasource.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model:TF_BackChatLiveData = self.datasource[indexPath.row]
        
        return self.getHeight(model: model)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "backChat", for: indexPath) as! TF_BackChatCell
        cell.cellwidth = self.tableview.frame.size.width
        cell.backgroundColor = UIColor.clear
        cell.selectionStyle = . none

        cell.isOrientationLandscape = false
       
        cell.tag = indexPath.row
        let model:TF_BackChatLiveData = self.datasource[indexPath.row]
       
        cell.setBackmodel(model: model)
        cell.urldelegate = self
      
        cell.cellGestueBlock =  {  [weak self](img) in
            guard let `self` = self else {
                return
            }
            
            DispatchQueue.main.async {
                let model1:TF_BackChatLiveData = self.datasource[cell.tag]
                model1.image = img
                let index:IndexPath = IndexPath.init(item: cell.tag, section: 0)
                self.tableview.reloadRows(at: [index], with: .none)
            }
          
        }
        return cell
    }
    
   
    
    func getHeight(model:TF_BackChatLiveData) -> CGFloat {
        

         var roleStr:String = ""
              
         if (model.role == .roleSpadmin) {
                    roleStr = "老师";
        
                }
                //=============== 如果是助教说的话 =================
              else if (model.role == .roleAdmin)
                {
                    roleStr = "助教";

                }

        if (model.imageURL.count>0) { //
            model.msg = "";
        } else {
            model.msg = model.msg
        }
        let nickname = model.nickname + " "
        let str:NSString = nickname + model.msg as NSString

        let contentDict:[AnyHashable:Any]? = TalkfunSharedTools.assembleAttributeString(str as String, boundingSize: CGSize(width: self.tableview.frame.size.width-35-16-12-16, height: 2000), fontSize: 14, shadow: false) as! [AnyHashable : Any]
     
        let attr:NSAttributedString = contentDict?["attributeStr"] as! NSAttributedString
       
        let AttributedString = NSMutableAttributedString.init(attributedString: attr)
        
        let attr33: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),]
        AttributedString.addAttributes(attr33, range: NSRange(location: 0, length: attr.length))
        let attr34: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),]
        AttributedString.addAttributes(attr34, range: NSRange(location: 0, length: model.nickname.count))
      
       
         self.url = "";
       
        if TalkfunSharedTools.isWhetherNoUrl(model.msg) {
            self.url = model.msg
        } else {
            self.urlArr = TalkfunSharedTools.getURLFromStr(model.msg) as! [Any]
            if self.urlArr.count > 0 {
                self.url = self.urlArr[0] as? String
            }
        }
      
        
        if roleStr.count > 0 {
    
            let attch = NSTextAttachment.init()
           
            attch.bounds = CGRect(x: 0, y: -3, width: 27, height: 15)
            let imageStr = NSAttributedString.init(attachment: attch)
            AttributedString.insert(imageStr, at: model.nickname.count+1)
            let Attri = NSAttributedString.init(string: " ")
            AttributedString.insert(Attri, at: model.nickname.count+2)
            let AttributeName: [NSAttributedString.Key : Any] = [.kern:5]
            AttributedString.addAttributes(AttributeName, range: NSRange(location: model.nickname.count+2, length: 1))
            
            
    
        }
        

        
        let font:UIFont? = UIFont.systemFont(ofSize: 14)
        
        let size = TalkfunSharedTools.sizeLabelToFit(AttributedString, width: self.tableview.frame.size.width-35-16-12-16, fontSize: font!)
        
        
    
      
        var imgHeight:CGFloat = 0;
        if (model.imageURL.count>0) {
            if (model.image != nil) {
                if (model.image.size.width == model.image.size.height) {
                    imgHeight = 96 + 8
                } else if (model.image.size.width > model.image.size.height) {
                    let proportion:CGFloat = model.image.size.width / 96
                    imgHeight = model.image.size.height / proportion + 8
                } else if (model.image.size.width < model.image.size.height){
                    imgHeight = 96+8
                }
            } else {
                imgHeight = 50
            }
       
      } else {
          imgHeight = 0;
      }
      return size.height+8+12+imgHeight;


    }
    
    func createUI() {
        
        self.tableview = UITableView.init(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
        self.tableview.delegate = self
        self.tableview.dataSource = self
        self.tableview.backgroundColor = UIColor.clear
        self.tableview.register(TF_BackChatCell.self, forCellReuseIdentifier: "backChat")
        self.tableview.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.view.addSubview(self.tableview)
        
        self.nodataView = UIView.init()
        self.nodataView.frame = self.view.bounds;
        self.view.addSubview(self.nodataView)
      
        let noImg = UIImageView.init()
        noImg.frame = CGRect(x: (self.nodataView.frame.size.width-200)/2.0, y: 60, width: 200, height: 150)
        noImg.image = UIImage.init(named: "HTLive.bundle/Default page_ask")
        self.nodataView.addSubview(noImg)
     
    
        let noLabel = UILabel.init()
        noLabel.text = "暂无聊天";
        noLabel.font = UIFont.PingFang(size: 16)
        noLabel.textColor = UIColor(red: 20/255.0, green: 23/255.0, blue: 26/255.0, alpha: 1.0)
        noLabel.textAlignment = .center
        noLabel.frame = CGRect(x: 0, y: 176, width: self.nodataView.frame.size.width, height: 22)
        self.nodataView.addSubview(noLabel)

    }
    
    //回放提问信息
  
    
    func updatePlayBackChatData(model:TF_BackChatLiveData)  {
        
        self.datasource.append(model)
       

        if self.datasource.count > 0 {
            self.nodataView.isHidden = true
        } else {
            self.nodataView.isHidden = false
        }
    }
  
    
    func urlClick(url:String) {
        self.delegate?.Backchat_clickToUrl(url: url)
    }
    
    
    func nsRange(from range:Range<String.Index>) -> NSRange {
        return NSRange(range,in: String.init())
       }

}
